<template>
  <div class="job-list">
    <div class="list-header">
      <div class="total-count">
        共找到 <span class="highlight">{{ total }}</span> 个职位
      </div>
      
      <div class="sort-options">
        <el-radio-group v-model="sortBy" @change="handleSortChange">
          <el-radio-button label="default">默认排序</el-radio-button>
          <el-radio-button label="latest">最新发布</el-radio-button>
          <el-radio-button label="salary">薪资最高</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <div class="list-content" v-loading="loading">
      <template v-if="jobs.length > 0">
        <job-card
          v-for="job in jobs"
          :key="job.id"
          :job="job"
          @apply="handleApply"
          @favorite="handleFavorite"
        />
      </template>
      
      <el-empty
        v-else-if="!loading"
        description="暂无符合条件的职位"
      />
    </div>

    <div class="list-footer">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import JobCard from './JobCard.vue'

// 列表数据
const jobs = ref([])
const total = ref(0)
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(20)

// 排序方式
const sortBy = ref('default')

// 获取职位列表
const fetchJobs = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const response = await jobApi.getJobs({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   sortBy: sortBy.value,
    //   ...props.filters
    // })
    // jobs.value = response.data.list
    // total.value = response.data.total
    
    // 模拟数据
    jobs.value = [
      {
        id: 1,
        title: '高级前端开发工程师',
        salary: '25-35k·13薪',
        companyLogo: '',
        companyName: '字节跳动',
        companySize: '10000人以上',
        companyIndustry: '互联网',
        city: '北京',
        experience: '3-5年',
        education: '本科',
        tags: ['React', 'Vue', 'TypeScript'],
        postTime: '2025-01-15 10:30:00',
        recruiterName: '张先生',
        recruiterTitle: 'HR',
        isFavorite: false
      },
      {
        id: 2,
        title: '资深前端开发工程师',
        salary: '30-45k·14薪',
        companyLogo: '',
        companyName: '腾讯科技',
        companySize: '10000人以上',
        companyIndustry: '互联网',
        city: '深圳',
        experience: '5-10年',
        education: '本科',
        tags: ['Vue', 'Node.js', '微前端'],
        postTime: '2025-01-15 09:15:00',
        recruiterName: '李女士',
        recruiterTitle: 'HRBP',
        isFavorite: true
      }
    ]
    total.value = 2
    
    // 模拟加载延迟
    setTimeout(() => {
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取职位列表失败', error)
    loading.value = false
    ElMessage.error('获取职位列表失败，请稍后再试')
  }
}

// 处理排序方式变化
const handleSortChange = () => {
  currentPage.value = 1
  fetchJobs()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchJobs()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchJobs()
}

// 处理投递简历
const handleApply = async (job) => {
  try {
    // 检查用户是否登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录后再投递简历')
      router.push({
        path: '/auth/login',
        query: { redirect: `/jobs/${job.id}` }
      })
      return
    }
    
    // 获取用户默认简历
    // const resume = await resumeApi.getDefaultResume()
    // if (!resume) {
    //   ElMessageBox.confirm(
    //     '您还没有创建简历，是否立即创建？',
    //     '提示',
    //     {
    //       confirmButtonText: '创建简历',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }
    //   ).then(() => {
    //     router.push('/resumes/create')
    //   })
    //   return
    // }
    
    // 确认投递
    await ElMessageBox.confirm(
      '确认要投递简历吗？',
      '提示',
      {
        confirmButtonText: '确认投递',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 调用投递API
    // await jobApi.applyJob({
    //   jobId: job.id,
    //   resumeId: resume.id
    // })
    
    ElMessage.success('投递成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('投递简历失败', error)
      ElMessage.error('投递失败，请稍后再试')
    }
  }
}

// 处理收藏/取消收藏
const handleFavorite = async ({ jobId, isFavorite }) => {
  try {
    // 检查用户是否登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录后再收藏职位')
      router.push({
        path: '/auth/login',
        query: { redirect: `/jobs/${jobId}` }
      })
      return
    }
    
    // 调用收藏/取消收藏API
    // if (isFavorite) {
    //   await jobApi.favoriteJob(jobId)
    // } else {
    //   await jobApi.unfavoriteJob(jobId)
    // }
    
    // 更新本地状态
    const job = jobs.value.find(j => j.id === jobId)
    if (job) {
      job.isFavorite = isFavorite
    }
    
    ElMessage.success(isFavorite ? '收藏成功' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败', error)
    ElMessage.error('操作失败，请稍后再试')
  }
}

// 接收筛选条件
const props = defineProps({
  filters: {
    type: Object,
    default: () => ({})
  }
})

// 监听筛选条件变化
watch(
  () => props.filters,
  () => {
    currentPage.value = 1
    fetchJobs()
  },
  { deep: true }
)

// 初始化
onMounted(() => {
  fetchJobs()
})
</script>

<style lang="scss" scoped>
.job-list {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-lg);
    
    .total-count {
      font-size: 0.9rem;
      color: var(--text-secondary);
      
      .highlight {
        color: var(--color-primary);
        font-weight: 600;
        margin: 0 4px;
      }
    }
  }
  
  .list-content {
    min-height: 400px;
    
    .job-card {
      margin-bottom: var(--spacing-md);
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .list-footer {
    margin-top: var(--spacing-xl);
    display: flex;
    justify-content: center;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .job-list {
    .list-header {
      flex-direction: column;
      gap: var(--spacing-md);
      
      .sort-options {
        width: 100%;
        
        .el-radio-group {
          width: 100%;
          display: flex;
          
          .el-radio-button {
            flex: 1;
            
            :deep(.el-radio-button__inner) {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style> 